package com.wgts.wgts.netmodle;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wgts.wgts.BuildConfig;
import com.wgts.wgts.MoHuApplication;
import com.wgts.wgts.mvp.view.activity.login.LoginActivity;
import com.wgts.wgts.tools.AppInfor;

import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 */

public class NetWorkFactory implements IGlobalManager{

    private static long netTime = 0;

    private static int indexForHost = 0;

    private final Gson gson;
    private static ArrayList<Retrofit> Retrofits;
    private static OkHttpClient sOkHttpClient;
    private static NetWorkFactory instance;

    private static final long DEFAULT_TIMEOUT = 10;


    private final static Object mRetrofitLock = new Object();


    private static ArrayList<Retrofit> getRetrofit() {
        if (Retrofits == null) {
            synchronized (mRetrofitLock) {
                if (Retrofits == null) {

                    Retrofits = new ArrayList<>();

                    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                        @Override
                        public void log(String message) {
                            //打印retrofit日志
                            Log.i("RetrofitLog","retrofitBack ======================= "+message);
                        }
                    });

                    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    //定制OkHttp
                    OkHttpClient.Builder builder = new OkHttpClient.Builder();
                    builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
                    builder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
                    builder.addInterceptor(loggingInterceptor);
                    sOkHttpClient = builder.build();
                    Retrofits.add(new Retrofit.Builder()
                            .baseUrl(BuildConfig.BASE_PING_IP1)
                            .client(sOkHttpClient)
                            .addConverterFactory(ResponseConverterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .build());
                    //RetrofitCache.getInstance().addRetrofit(sRetrofit);
                    Retrofits.add(new Retrofit.Builder()
                            .baseUrl(BuildConfig.BASE_PING_IP2)
                            .client(sOkHttpClient)
                            .addConverterFactory(ResponseConverterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .build());

                    Retrofits.add(new Retrofit.Builder()
                            .baseUrl(BuildConfig.BASE_PING_IP3)
                            .client(sOkHttpClient)
                            .addConverterFactory(ResponseConverterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .build());

                    Retrofits.add(new Retrofit.Builder()
                            .baseUrl(BuildConfig.BASE_PING_IP4)
                            .client(sOkHttpClient)
                            .addConverterFactory(ResponseConverterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                            .build());
                }
            }
        }
        return Retrofits;
    }


    public <T> T get(Class<T> tClass) {
        return getRetrofit().get(indexForHost).create(tClass);
    }



    private NetWorkFactory(){
        gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd hh:mm:ss")
                .create();
    }



    public static NetWorkFactory getInstance(AppOkHttpClient okHttpClient) {
        if (instance == null) {
            synchronized (NetWorkFactory.class) {
                if (instance == null) {
                    instance = new NetWorkFactory();
                }
            }
        }
        return instance;
    }


    @SuppressWarnings("unchecked")
    public <T> T createService(Class<T> serviceClass){
        T t = getRetrofit().get(indexForHost).create(serviceClass);
        return (T) Proxy.newProxyInstance(serviceClass.getClassLoader(), new Class<?>[] { serviceClass }, new ProxyHandler(t, this));
    }




    @Override
    public void exitLogin() {
        // Cancel all the netWorkRequest
        //sOkHttpClient.dispatcher().cancelAll();

        // Goto the home page
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {

                //Toast.makeText(BaseApplication.getContext(), "Token is not existed!!", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(MoHuApplication.getInstance(), LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                MoHuApplication.getInstance().startActivity(intent);
                AppInfor.getInstance().setAccessToken("");
                AppInfor.getInstance().setRefreshToken("");
                AppInfor.getInstance().setUserState(0);
            }
        });
    }

    public static void setIndexForHost(int indexForHost) {
        NetWorkFactory.indexForHost = indexForHost;
    }

    public static int getIndexForHost() {
        return indexForHost;
    }

    public static ArrayList<Retrofit> getRetrofits() {
        return Retrofits;
    }

    public static OkHttpClient getsOkHttpClient() {
        return sOkHttpClient;
    }

    public static long getNetTime() {
        return netTime;
    }

    public static void setNetTime(long netTime) {
        NetWorkFactory.netTime = netTime;
    }
}
